import { type Conversion, type AIAgent } from './interface'
import { ChatSession } from './chat-session'
import { getChatHistory } from '@/utils/api'
import { aiAgentStore } from '../stores/ai-agent'
import { createAndEnsureAIAgent } from './lib'

class ChatSessionManager {
  //单例
  private static instance: ChatSessionManager
  chatHistory: Conversion[] = [] as Conversion[]

  currentChatSession: ChatSession | undefined = undefined

  private constructor() {
    console.log('ChatSessionManager instance created.')
  }

  public static getInstance(): ChatSessionManager {
    if (!ChatSessionManager.instance) {
      ChatSessionManager.instance = new ChatSessionManager()
    }
    return ChatSessionManager.instance
  }
  public setup(): void {
    console.log('Called setup.')
  }

  public async getChatHistory(): Promise<Array<Conversion>> {
    try {
      const data = await getChatHistory()

      this.chatHistory = data.list.map((item: any) => {
        const agentData = item.agent_data
        const model: AIAgent = createAndEnsureAIAgent(agentData)
        const history: Conversion = {
          conversionId: item.session_id,
          conversionName: item.title,
          agentInfo: model,
          createTime: item.create_time,
          updateTime: item.update_time
        }
        return history
      })

      const agentStore = aiAgentStore()
      agentStore.setConversionHistory(this.chatHistory)

      return this.chatHistory
    } catch (error) {
      console.error('Error fetching chat history:', error)
      throw error
    }
  }

  // switchChatSession(chatSession:ChatSession){
  //   this.currentChatSession = chatSession;
  // }
}

const chatMgr = ChatSessionManager.getInstance()
export default chatMgr
